package io.renren.modules.api.controller;

import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.api.annotation.LoginUser;
import io.renren.modules.api.entity.*;
import io.renren.modules.api.service.*;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.SjDriverService;
import io.renren.modules.psnetpoint.entity.PsNetPointEntity;
import io.renren.modules.psnetpoint.service.PsNetPointService;
import io.renren.modules.psorder.entity.PsOrderEntity;
import io.renren.modules.psorder.service.PsOrderService;
import io.renren.modules.user.entity.PsBannerEntity;
import io.renren.modules.user.service.PsBannerService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 普通用户强相关性接口
 * Created by WDJ on 2017/12/4.
 */
@RestController
@RequestMapping("/normalUser")
public class ApiUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private PsOrderService psOrderService;
    @Autowired
    private SjDriverService driverService;
    @Autowired
    private YhEvaluateDriverService yhEvaluateDriverService;
    @Autowired
    private PsPushRecordsService psPushRecordsService;
    @Autowired
    private PsCouponService psCouponService;
    @Autowired
    private UserCouponsService userCouponsService;
    @Autowired
    private UserFrequentlyRouteService userFrequentlyRouteService;
    @Autowired
    private UserFrequentlyRouteSectionService userFrequentlyRouteSectionService;
    @Autowired
    private UserCollectDriverService userCollectDriverService;
    @Autowired
    private PsNetPointService psNetPointService;
    @Autowired
    private PsBannerService psBannerService;
    @Autowired
    private PsOrderRouteSectionService psOrderRouteSectionService;
    @Autowired
    private PsOrderLogisticsRecordService psOrderLogisticsRecordService;

    @Value("${qwj.imagesPath}")
    String ROOT;

    /**
     * 获取用户信息
     */
    @GetMapping("userInfo")
    public R userInfo(@LoginUser UserEntity user){
        return R.ok().put("user", user);
    }

    /**
     * 用户更新registrationId
     */
    @PostMapping("updateUserRegId")
    public R updateUserRegId(@LoginUser UserEntity user,String registrationId){
        String regId = user.getRegistrationId();
        if (registrationId == null || "".equals(registrationId)) {
            return R.error(-1,"传的registrationId为null或空串!");
        }
        if (!regId.equals(registrationId)) {
            user.setRegistrationId(registrationId);
            userService.update(user);
        }

        return R.ok("更新成功!");
    }

    /**
     * 用户下单
     * @param user
     * @param psOrder
     * @param registrationId
     * @return
     */
    @PostMapping("submitPsOrder")
    public R submitPsOrder(@LoginUser UserEntity user,PsOrderEntity psOrder,String registrationId,
                           String psOrderRouteSections){
        if (registrationId == null && "".equals(registrationId)) {
            return R.error(-1,"极光Id无效或为空,下单失败!");
        }
        //将接受的json字符串初步转成路段对象集合
        List<PsOrderRouteSectionEntity> psOrderRouteSectionList =
                JSONArray.parseArray(psOrderRouteSections,PsOrderRouteSectionEntity.class);
        //根据初步路段对象集合转成系统需要的路段对象集合
        for (int i=0 ; i < psOrderRouteSectionList.size();i++) {
            if (i > 0){
                psOrderRouteSectionList.get(i).setStartName(psOrderRouteSectionList.get(i-1).getEndName());
                psOrderRouteSectionList.get(i).setStartNameDetail(psOrderRouteSectionList.get(i-1).getEndNameDetail());
                psOrderRouteSectionList.get(i).setStartLng(psOrderRouteSectionList.get(i-1).getEndLng());
                psOrderRouteSectionList.get(i).setStartLat(psOrderRouteSectionList.get(i-1).getEndLat());
                psOrderRouteSectionList.get(i).setSortNum(psOrderRouteSectionList.get(i).getSortNum()-1);
            }
        }
        psOrderRouteSectionList.remove(0);

        user.setRegistrationId(registrationId);
        //保存乘客极光Id
        userService.update(user);
        //订单号
        psOrder.setOrdernum(OrderUtil.getOutTradeNo(OrderUtil.ORDER_TYPE_PS));
        //发单人用户ID
        psOrder.setUserId(user.getUserId());
        //发单人电话
        psOrder.setUserPhone(user.getPhone());
        //发单人姓名
        psOrder.setUserName(user.getRealname());
        //发单时间
        psOrder.setCreateTime(new Date());
        //订单状态 初始值"0"  未完成
        psOrder.setOrderStatus("0");
        //支付状态
        psOrder.setPayStatus("0");
        //是否是预约订单
        psOrder.setAppointment(false);
//        //计算行驶距离(高德),单位为米
//        String ditanceValue = AutoNaviUtils.calculateCarDistance(psOrder.getStartLng(),psOrder.getStartLat(),
//                psOrder.getEndLng(),psOrder.getEndLat());
        //计算订单距离(可能是多目的地),单位为米
        String ditanceValue = AutoNaviUtils.evaluateOrderDistance(psOrderRouteSectionList);

        //设置订单距离,单位为千米
        psOrder.setDistance(DataTypeUtils.metresStringToKiloMeter(ditanceValue));

        //计算订单金额
        AutoNaviUtils.evaluateOrderMoneyByType2(psOrder,ditanceValue); //6种车型方案
        psOrderService.save(psOrder);
        for (PsOrderRouteSectionEntity psOrderRouteSection :psOrderRouteSectionList) {
            psOrderRouteSection.setOrdernum(psOrder.getOrdernum());
            psOrderRouteSectionService.save(psOrderRouteSection);
        }
        List<String> regIds = findDriverAround(psOrder.getStartLng(),psOrder.getStartLat(),psOrder.getOrdernum());
//        if( DriverRegistrationId == null ) {
//            return R.error(-3,"司机极光Id为null,下单失败!");
//        }
        if ( regIds.size() == 0 ) {
            return R.error(-4,"附近没有司机，下单失败!");
        }

        //推送若包含多目的地，会报超字节异常
        List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
        JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
        for (String regId:regIds) {
            QmSendPush.sendPushToDriver(regId,psOrder,null);
        }

        return R.ok().put("psOrder",psOrder).put("destinationList",destinationList);
    }


    /**
     * 用户下预约配送订单
     */
    @PostMapping("submitAppointMentPsOrder")
    public R submitAppointMentPsOrder(@LoginUser UserEntity user,PsOrderEntity psOrder,String registrationId,
                                      String psOrderRouteSections){
        if (registrationId == null && "".equals(registrationId)) {
            return R.error(-1,"光Id无效或为空,下单失败!");
        }
        //将接受的json字符串初步转成路段对象集合
        List<PsOrderRouteSectionEntity> psOrderRouteSectionList =
                JSONArray.parseArray(psOrderRouteSections,PsOrderRouteSectionEntity.class);
        //根据初步路段对象集合转成系统需要的路段对象集合
        for (int i=0 ; i < psOrderRouteSectionList.size();i++) {
            if (i > 0){
                psOrderRouteSectionList.get(i).setStartName(psOrderRouteSectionList.get(i-1).getEndName());
                psOrderRouteSectionList.get(i).setStartNameDetail(psOrderRouteSectionList.get(i-1).getEndNameDetail());
                psOrderRouteSectionList.get(i).setStartLng(psOrderRouteSectionList.get(i-1).getEndLng());
                psOrderRouteSectionList.get(i).setStartLat(psOrderRouteSectionList.get(i-1).getEndLat());
                psOrderRouteSectionList.get(i).setSortNum(psOrderRouteSectionList.get(i).getSortNum()-1);
            }
        }
        psOrderRouteSectionList.remove(0);
        user.setRegistrationId(registrationId);
        //保存乘客极光Id
        userService.update(user);
        //订单号
        psOrder.setOrdernum(OrderUtil.getOutTradeNo(OrderUtil.ORDER_TYPE_PS));
        //发单人用户ID
        psOrder.setUserId(user.getUserId());
        //发单人电话
        psOrder.setUserPhone(user.getPhone());
        //发单人姓名
        psOrder.setUserName(user.getRealname());
        //发单时间
        psOrder.setCreateTime(new Date());
        //订单状态 初始值"0"  未完成
        psOrder.setOrderStatus("0");
        //支付状态
        psOrder.setPayStatus("0");
        //是否是预约订单
        psOrder.setAppointment(true);
        //计算行驶距离(高德),单位为米
        String ditanceValue = AutoNaviUtils.calculateCarDistance(psOrder.getStartLng(),psOrder.getStartLat(),
                psOrder.getEndLng(),psOrder.getEndLat());

        //设置订单距离,单位为千米
        psOrder.setDistance(DataTypeUtils.metresStringToKiloMeter(ditanceValue));

        //计算订单金额
        AutoNaviUtils.evaluateOrderMoneyByType2(psOrder,ditanceValue); //6种车型方案
        psOrderService.save(psOrder);
        for (PsOrderRouteSectionEntity psOrderRouteSection :psOrderRouteSectionList) {
            psOrderRouteSection.setOrdernum(psOrder.getOrdernum());
            psOrderRouteSectionService.save(psOrderRouteSection);
        }
        List<String> regIds = findDriverAround(psOrder.getStartLng(),psOrder.getStartLat(),psOrder.getOrdernum());
        if ( regIds.size() == 0 ) {
            return R.error(-4,"附近没有司机，下单失败!");
        }

        //推送若包含多目的地，会报超字节异常
        List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
        JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
        for (String regId:regIds) {
            QmSendPush.sendPushToDriver(regId,psOrder,null);
        }

        return R.ok("预约订单成功!").put("psOrder",psOrder).put("destinationList",destinationList);
    }

    /**
     * 高德云周边检索
     */
    public List<String> findDriverAround (String longitude,String latitude,String orderNum) {
        String centerLocation = longitude+","+latitude;
        String paraForSign = "center="+centerLocation+"&key="+QwjGlobal.AUTONAVI_WEB_KEY+"&limit=100"
                +"&radius=5000"+"&tableid="+QwjGlobal.AUTONAVI_HTTP_TABLE_ID;
        String privateKey = QwjGlobal.AUTONAVI_WEB_PRIVATE_KEY;
        String sig = MD5Util.MD5Encode(paraForSign+privateKey, "utf-8");

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("center",centerLocation);
        paraMap.put("key", QwjGlobal.AUTONAVI_WEB_KEY);
        paraMap.put("limit", "100");
        paraMap.put("radius", "5000");
        paraMap.put("sig", sig);
        paraMap.put("tableid", QwjGlobal.AUTONAVI_HTTP_TABLE_ID);

//        String sr = HttpUtil.sendPost(QwjGlobal.AUTONAVI_HTTP_SEARCH_AROUND_URL,paraMap);
        String sr = HttpClientHelper.requestBodyString(QwjGlobal.AUTONAVI_HTTP_SEARCH_AROUND_URL,paraMap);
        Map<String, Object> resultMap = QmJsonUtils.parseJSON2Map(sr);
//  		int status = Integer.valueOf(String.valueOf(resultMap.get("status"))).intValue();
        List<String> regIds = new ArrayList<>();
        @SuppressWarnings("unchecked")
        ArrayList<Map<String, Object>> listDatas = (ArrayList<Map<String, Object>>) resultMap.get("datas");
        if(listDatas.size() == 0) {
            return regIds;
        }
        Map<String, Object> datas = listDatas.get(0);

        for (Map<String, Object> data:listDatas) {
            String driverUserName = String.valueOf(data.get("_name")); //高德云检索出最近出车的司机
            SjDriverEntity driver = driverService.queryObjectByUserName(driverUserName);
            String registrationId = driver.getRegistrationId();
            if (registrationId != null && !"".equals(registrationId)) {
                regIds.add(registrationId);
                //推送一个就存到推送记录表
                PsPushRecordsEntity psPushRecordsEntity = new PsPushRecordsEntity();
                psPushRecordsEntity.setOrdernum(orderNum);
                psPushRecordsEntity.setPushTime(new Date());
                psPushRecordsEntity.setDriveruser(driverUserName);
                psPushRecordsEntity.setRegistrationId(registrationId);
                psPushRecordsService.save(psPushRecordsEntity);
            }

        }

//        return registrationId;
        return regIds;
    }

    public PushPayload buildPushObject_android_and_ios(String registrationId,String pushJson) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
//                .setNotification(Notification.newBuilder()
//                		.setAlert("alert content")
//                		.addPlatformNotification(AndroidNotification.newBuilder()
//                				.setTitle("Android Title").build())
//                		.addPlatformNotification(IosNotification.newBuilder()
//                				.incrBadge(1)
//                				.addExtra("extra_key", "extra_value").build())
//                		.build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(pushJson)
                        .build())
                .build();

    }

    /**
     * 上传照片
     * @param file 传body参数里面要指定是file
     * @param user 登录的用户，注解根据传的tokne处理，不用传参
     * @param type 传的文件类型, 默认0，表示上传头像
     * @return
     */
    @PostMapping(value = "/uploadImg", headers = {"Content-Type=multipart/form-data"})
    public R uploadImg(@RequestBody MultipartFile file, @LoginUser UserEntity user, String type) {

        String filePath = "";
        String filename = "";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            if (file.getSize() > 10240000) {
                throw new RRException("上传失败：文件大小不能超过10M");
            }
            //判断是否上传过头像
            if (user.getAvatar() != null) {
                File fileToDelete = new File(ROOT+user.getAvatar());
                if (fileToDelete.exists() && fileToDelete.isFile()) {
                    fileToDelete.delete();
                }
            }
            try {
                //提取后缀
                String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                if("0".equals(type)){
                    filename = user.getUserId()+"_face_" + DateUtils.format(new Date(), "yyyyMMddHHmmss")+RandomUtils.generateString(4) + postfix;
                    user.setAvatar(filename);
                }else{ //除了身份证以外的上传图片
                    filename = user.getUserId()+"_bl_" + DateUtils.format(new Date(), "yyyyMMddHHmmss")+RandomUtils.generateString(4) + postfix;
//                        user.setBusinessLicence(filename);
                }
                userService.update(user);
                // 文件保存路径
                filePath = ROOT+ filename;
                File saveDir = new File(filePath);
                //判断目标文件所在的目录是否存在
                if (!saveDir.getParentFile().exists()) {
                    //如果目标文件所在的目录不存在，则创建父目录
                    saveDir.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(saveDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new RRException("上传失败:请添加上传文件！");
        }
        System.out.println("filePath:" + filePath);

        return R.ok().put("url", filePath);//.put("fileId",ossEntity.getId());
    }

    /**
     * 用户查询已完成配送订单
     */
    @GetMapping("queryCompletedPsOrder")
    public R queryCompletedPsOrder(@LoginUser UserEntity user){
        List<PsOrderEntity> psOrders = psOrderService.userQueryCompletedPsOrder(user.getUserId());
        if (psOrders != null ){
            for (PsOrderEntity psOrder:psOrders) {
                List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
                JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
                psOrder.setDestinationJsonArray(destinationJsonArray);
            }
        }
        return R.ok().put("completedPsOrders",psOrders);
    }

    /**
     * 用户查询进行中的配送订单
     */
    @GetMapping("queryOnGoingPsOrder")
    public R queryOnGoingPsOrder(@LoginUser UserEntity user){
        List<PsOrderEntity> psOrders = psOrderService.userQueryOnGoingPsOrder(user.getUserId());
        if (psOrders != null ){
            for (PsOrderEntity psOrder:psOrders) {
                List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
                JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
                psOrder.setDestinationJsonArray(destinationJsonArray);
            }
        }
        return R.ok().put("onGoingPsOrders",psOrders);
    }

    /**
     * 用户查询已取消的配送订单
     */
    @GetMapping("queryCancelPsOrder")
    public R queryCancelPsOrder(@LoginUser UserEntity user){
        List<PsOrderEntity> psOrders = psOrderService.userQueryCancelPsOrder(user.getUserId());
        if (psOrders != null ){
            for (PsOrderEntity psOrder:psOrders) {
                List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(psOrder.getOrdernum());
                JSONArray destinationJsonArray = JSONArray.parseArray(JSON.toJSONString(destinationList));
                psOrder.setDestinationJsonArray(destinationJsonArray);
            }
        }
        return R.ok().put("cancelPsOrder",psOrders);
    }

    /**
     * 用户取消订单
     */
    @PostMapping("cancelPsOrder")
    public R cancelPsOrder(@LoginUser UserEntity user,String ordernum){
        PsOrderEntity psOrder  = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        userService.cancelPsOrder(psOrder);

        return R.ok();
    }

    /**
     * 用户评价配送司机
     */
    @PostMapping("evaluatePsDriver")
    public R evaluatePsDriver(@LoginUser UserEntity user,String ordernum,int starRank,String serverItem,String comment){
        PsOrderEntity psOrder  = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        YhEvaluateDriverEntity userEvaluate = new YhEvaluateDriverEntity();
        userEvaluate.setOrdernum(ordernum);
        userEvaluate.setUserId(user.getUserId());
        userEvaluate.setDriverId(psOrder.getDriverId());
        userEvaluate.setCreateTime(new Date());
        userEvaluate.setStarRank(starRank);
        userEvaluate.setComment(comment);

        String[] items = serverItem.split(",");
        if (items.length != 4) {
            throw new RRException("serverItem参数格式错误",-4);
        }
        userEvaluate.setRlzq("1".equals(items[0])); //认路准确
        userEvaluate.setRqzd("1".equals(items[0])); //热情周到
        userEvaluate.setHss("1".equals(items[0]));  //很守时
        userEvaluate.setSfhl("1".equals(items[0])); //收费合理
        yhEvaluateDriverService.save(userEvaluate);
        psOrder.setEvaluated(true);
        psOrderService.update(psOrder);  //设置订单已评价
        //todo 计算下司机平均星等并写入数据库


        return R.ok();
    }

    /**
     * 用户选择现金支付
     */
    @PostMapping("selectCashPay")
    public R selectCashPay(@LoginUser UserEntity user,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!user.getUserId().equals(psOrder.getUserId())) {
            return R.error(-3,"非法操作,与订单用户不匹配!");
        }
        userService.selectCashPay(psOrder);

        return R.ok();
    }

    /**
     * 用户查看当前位置
     */
    @PostMapping("queryCurLocByOrdernum")
    public R queryCurLocByOrdernum(@LoginUser UserEntity user,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!user.getUserId().equals(psOrder.getUserId())) {
            return R.error(-3,"非法操作,与订单用户不匹配!");
        }
        Map<String,Object> paraBack = new HashMap();
        paraBack.put("curLng",psOrder.getCurLng());
        paraBack.put("curLat",psOrder.getCurLat());

        return R.ok(paraBack);
    }

    /**
     * 用户获得优惠券
     */
    @PostMapping("getCoupon")
    public R getCoupon(@LoginUser UserEntity user,Long couponid){
        //如果用户已经有这张优惠券
        if (userCouponsService.isUserHaveCoupon(user,couponid)) {
            return R.error(-3,"用户已经领过这张优惠券了!");
        }
        PsCouponEntity psCouponEntity = psCouponService.queryObject(couponid);
        UserCouponsEntity userCouponsEntity = new UserCouponsEntity();
        userCouponsEntity.setPsCouponId(couponid);
        userCouponsEntity.setUserId(user.getUserId());
        userCouponsEntity.setStartTime(psCouponEntity.getStartTime());
        userCouponsEntity.setEndTime(psCouponEntity.getEndTime());
        userCouponsEntity.setStatus(1); //未使用
        userCouponsEntity.setCount(1);
        userCouponsService.save(userCouponsEntity);

        return R.ok("成功获得优惠券!");
    }

    /**
     * 用户查询已获得优惠券列表
     */
    @GetMapping("queryCoupons")
    public R queryCoupons(@LoginUser UserEntity user){
        List<PsCouponEntity> psCouponEntities = psCouponService.queryListByUserId(user.getUserId());

        return R.ok().put("psCouponEntities",psCouponEntities);
    }

    /**
     * 用户选择优惠券付款
     */
    @PostMapping("selectCouponForPay")
    public R selectCouponForPay(@LoginUser UserEntity user,String ordernum,Long couponid){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);
        if (psOrder == null) {
            return R.error(-1,"订单不存在!");
        }
        if (!user.getUserId().equals(psOrder.getUserId())) {
            return R.error(-3,"非法操作,与订单用户不匹配!");
        }
        //验证优惠券没过期
        PsCouponEntity psCouponEntity = psCouponService.queryObject(couponid);
        if (psCouponEntity != null && psCouponEntity.getStatus()) {
             psOrder.setTotalPrice(psOrder.getTotalPrice().subtract(psCouponEntity.getPrice()));
             psOrder.setPsCouponId(couponid);
             psOrderService.update(psOrder);
            return R.ok().put("psOrder",psOrder);
        }

        return R.error(-4,"优惠券失效或无法使用!");
    }

    /**
     * 添加常用路线
     */
    @PostMapping("addFrequentlyRoute")
    public R addFrequentlyRoute(@LoginUser UserEntity user,UserFrequentlyRouteEntity userFrequentlyRoute,
                                 String userFrequentlyRouteSections){
        userFrequentlyRoute.setUserId(user.getUserId());
        //将接受的json字符串初步转成路段对象集合
        List<UserFrequentlyRouteSectionEntity> userFrequentlyRouteSectionEntities = JSONArray.parseArray(userFrequentlyRouteSections,UserFrequentlyRouteSectionEntity.class);
        //根据初步路段对象集合转成系统需要的路段对象集合
        for (int i=0 ; i < userFrequentlyRouteSectionEntities.size();i++) {
            if (i > 0){
                userFrequentlyRouteSectionEntities.get(i).setStartName(userFrequentlyRouteSectionEntities.get(i-1).getEndName());
                userFrequentlyRouteSectionEntities.get(i).setStartNameDetail(userFrequentlyRouteSectionEntities.get(i-1).getEndNameDetail());
                userFrequentlyRouteSectionEntities.get(i).setStartLng(userFrequentlyRouteSectionEntities.get(i-1).getEndLng());
                userFrequentlyRouteSectionEntities.get(i).setStartLat(userFrequentlyRouteSectionEntities.get(i-1).getEndLat());
                userFrequentlyRouteSectionEntities.get(i).setSortNum(userFrequentlyRouteSectionEntities.get(i).getSortNum()-1);
            }
        }
        userFrequentlyRouteSectionEntities.remove(0);

        userFrequentlyRouteService.addFrequentlyRoute(userFrequentlyRoute,userFrequentlyRouteSectionEntities);

        return R.ok();
    }

    /**
     * 查询常用路线列表
     */
    @PostMapping("queryFrequentlyRoute")
    public R queryFrequentlyRoute(@LoginUser UserEntity user){
        List<Map<String,Object>> userFrequentlyRouteEntities = userFrequentlyRouteService.queryByUserId(user.getUserId());
        for (Map map:userFrequentlyRouteEntities) {
            List<Map<String,Object>> userFrequentlyRouteSectionEntities  = userFrequentlyRouteSectionService.queryListMapByRouteId((Long) map.get("id"));
            map.put("destinations",userFrequentlyRouteSectionEntities);
        }

        return R.ok().put("userFrequentlyRouteEntities",userFrequentlyRouteEntities);
    }

    /**
     * 删除常用路线
     */
    @PostMapping("deleteFrequentlyRoute")
    public R deleteFrequentlyRoute(@LoginUser UserEntity user,Long routeId){
        userService.deleteFrequentlyRoute(routeId);

        return R.ok();
    }

    /**
     * 修改常用路线
     */
    @PostMapping("modifyFrequentlyRoute")
    public R modifyFrequentlyRoute(@LoginUser UserEntity user,Long routeId,String userFrequentlyRouteSections){
        UserFrequentlyRouteEntity userFrequentlyRouteEntity = userFrequentlyRouteService.queryObject(routeId);
        //将接受的json字符串初步转成路段对象集合
        List<UserFrequentlyRouteSectionEntity> userFrequentlyRouteSectionEntities =
                JSONArray.parseArray(userFrequentlyRouteSections,UserFrequentlyRouteSectionEntity.class);
        //根据初步路段对象集合转成系统需要的路段对象集合
        for (int i=0 ; i < userFrequentlyRouteSectionEntities.size();i++) {
            if (i > 0){
                userFrequentlyRouteSectionEntities.get(i).setStartName(userFrequentlyRouteSectionEntities.get(i-1).getEndName());
                userFrequentlyRouteSectionEntities.get(i).setStartNameDetail(userFrequentlyRouteSectionEntities.get(i-1).getEndNameDetail());
                userFrequentlyRouteSectionEntities.get(i).setStartLng(userFrequentlyRouteSectionEntities.get(i-1).getEndLng());
                userFrequentlyRouteSectionEntities.get(i).setStartLat(userFrequentlyRouteSectionEntities.get(i-1).getEndLat());
                userFrequentlyRouteSectionEntities.get(i).setSortNum(userFrequentlyRouteSectionEntities.get(i).getSortNum()-1);
            }
        }
        userFrequentlyRouteSectionEntities.remove(0);

        userFrequentlyRouteService.modifyFrequentlyRoute(userFrequentlyRouteEntity,userFrequentlyRouteSectionEntities);

        return R.ok();
    }

    /**
     * 使用常用路线
     */
    @PostMapping("chooseFrequentlyRoute")
    public R chooseFrequentlyRoute(@LoginUser UserEntity user,Long routeId){
        List<UserFrequentlyRouteSectionEntity> userFrequentlyRouteSections =
                userFrequentlyRouteSectionService.queryListByRouteId(routeId);

        return R.ok().put("userFrequentlyRouteSections",userFrequentlyRouteSections);
    }

    /**
     * 用户查看接单的司机详情
     */
    @PostMapping("queryPsOrderDriverInfo")
    public R queryPsOrderDriverInfo(@LoginUser UserEntity user,Long driverId){
        SjDriverEntity driver = driverService.queryObject(driverId);
        //查出这个司机最近20条评价记录
        List<YhEvaluateDriverEntity> yhEvaluateDriverEntities = yhEvaluateDriverService.queryEvaluatesByDriverId(driverId);

        return R.ok().put("driver", driver).put("yhEvaluateDriverEntities",yhEvaluateDriverEntities);
    }

    /**
     * 用户收藏司机
     */
    @PostMapping("collectDriver")
    public R collectDriver(@LoginUser UserEntity user,Long driverId){
        //判断用户是否已经收藏该司机
        Map<String,Object> params = new HashedMap();
        params.put("userId",user.getUserId());
        params.put("driverId",driverId);
        List<UserCollectDriverEntity> userCollectDrivers = userCollectDriverService.queryList(params);
        if ( userCollectDrivers.size() > 0 ) {  //说明已收藏该司机
            R.error(-3,"用户已经收藏该司机");
        }
        UserCollectDriverEntity userCollectDriverEntity = new UserCollectDriverEntity();
        userCollectDriverEntity.setUserId(user.getUserId());
        userCollectDriverEntity.setDriverId(driverId);
        userCollectDriverEntity.setCreateTime(new Date());
        userCollectDriverService.save(userCollectDriverEntity);

        return R.ok();
    }

    /**
     * 用户查询收藏的司机列表
     */
    @PostMapping("queryCollectedDrivers")
    public R queryCollectedDrivers(@LoginUser UserEntity user){
        List<SjDriverEntity> driverEntities = driverService.queryCollectedListByUserId(user.getUserId());

        return R.ok().put("driverEntities",driverEntities);
    }

    /**
     * 用户查询附近网点
     */
    @PostMapping("queryNearByNetPoint")
    public R queryNearByNetPoint(@LoginUser UserEntity user,String longitude,String latitude,String keyword){
        //根据经纬度查询附近20公里的网点信息

        Map<String, Object> params = new HashedMap();
        List<PsNetPointEntity> psNetPointList = psNetPointService.queryList(params);
        List<PsNetPointEntity> removeList = new ArrayList<>(); //临时集合待删除集合，遍历时删除会报错
        //如果不包含搜索关键字，则移除
        if ( keyword != null && !"".equals(keyword) ){
            for (PsNetPointEntity psNetPoint:psNetPointList) {
                if (!psNetPoint.getPointName().contains(keyword)){
                    removeList.add(psNetPoint);
                }
            }
        }
        psNetPointList.removeAll(removeList);

        return R.ok().put("psNetPointList",psNetPointList);
    }

    /**
     * 计算选定起点终点后的价格
     */
    @PostMapping("evaluateMoneyByType")
    public R evaluateMoneyByType(@LoginUser UserEntity user,String type,String psOrderRouteSections){
        List<PsOrderRouteSectionEntity> newList =
                JSONArray.parseArray(psOrderRouteSections,PsOrderRouteSectionEntity.class);
        //根据初步路段对象集合转成系统需要的路段对象集合
        for (int i=0 ; i < newList.size();i++) {
            if (i > 0){
                newList.get(i).setStartName(newList.get(i-1).getEndName());
                newList.get(i).setStartNameDetail(newList.get(i-1).getEndNameDetail());
                newList.get(i).setStartLng(newList.get(i-1).getEndLng());
                newList.get(i).setStartLat(newList.get(i-1).getEndLat());
                newList.get(i).setSortNum(newList.get(i).getSortNum()-1);
            }
        }
        newList.remove(0);

        String ditanceValue = AutoNaviUtils.evaluateOrderDistance(newList);
        double douleKiloMetres = (DataTypeUtils.stringToDouble(ditanceValue))/1000;
        double orderMoney = 0.0;
        double passKiloMetres = 0.0; //超里程数(公里),默认为0表示默认5公里内
        if ( douleKiloMetres - 5.0 > 0 ) {
            passKiloMetres = douleKiloMetres - 5.0;
        }
        if ("1".equals(type)) {                 //同城小件
            orderMoney = passKiloMetres*3 + 20.0;
        } else if ("2".equals(type)) {          //小面包
            orderMoney = passKiloMetres*3 + 30.0;
        } else if ("3".equals(type)) {          //中面包
            orderMoney = passKiloMetres*5 + 60.0;
        }  else if ("4".equals(type)) {         //依维柯
            orderMoney = passKiloMetres*6 + 70.0;
        }else if ("5".equals(type)) {           //厢货
            orderMoney = passKiloMetres*6 + 90.0;
        }else if ("6".equals(type)) {           //冷链
            orderMoney = passKiloMetres*8 + 160.0;
        }
        DecimalFormat df = new DecimalFormat("#.00");

        return R.ok().put("orderMoney",df.format(orderMoney));
    }

    /**
     * 用户我的界面接口
     */
    @PostMapping("queryMineInfo")
    public R queryMineInfo(@LoginUser UserEntity user){
        Map<String,Object> mineInfo = userService.queryMineInfo(user.getUserId());

        return R.ok().put("mineInfo",mineInfo);
    }

    /**
     * 兑换2元优惠券
     */
    @PostMapping("exchangeTwoCoupon")
    public R exchangeTwoCoupon(@LoginUser UserEntity user){
        //先判断积分够不够
          if (user.getBonusPoints().intValue() < 998) {
              return R.error(-1,"积分不够!");
          }
        //够就兑换
        user.setBonusPoints(user.getBonusPoints() - 998); //减去积分
        //领取优惠券
        userService.getCouponById(user,new Long((long)3));

        return R.ok();
    }

    /**
     * 兑换4元优惠券
     */
    @PostMapping("exchangeFourCoupon")
    public R exchangeFourCoupon(@LoginUser UserEntity user){
        //先判断积分够不够
        if (user.getBonusPoints().intValue() < 1398) {
            return R.error(-1,"积分不够!");
        }
        //够就兑换
        user.setBonusPoints(user.getBonusPoints() - 1398); //减去积分
        //领取优惠券
        userService.getCouponById(user,new Long((long)3));

        return R.ok();
    }

    /**
     * 获得首页banner图
     */
    @AuthIgnore
    @GetMapping("getHomeBanners")
    public R getHomeBanners(){
        Map<String,Object> params = new HashedMap();
        params.put("type","1"); //查询客户端首页banner图
        List<PsBannerEntity> psBannerEntities = psBannerService.queryList(params);

        return R.ok().put("psBannerEntities",psBannerEntities);
    }

    /**
     * 用户修改昵称
     */
    @PostMapping("modifyNickName")
    public R modifyNickName(@LoginUser UserEntity user,String nickname){
        user.setNickname(nickname);
        userService.update(user);
        return R.ok();
    }

    /**
     * 用户修改性别
     */
    @PostMapping("modifySex")
    public R modifySex(@LoginUser UserEntity user,String sex){
        user.setSex(sex);
        userService.update(user);
        return R.ok();
    }

    /**
     * 用户修改联系号码
     */
    @PostMapping("modifyPhone")
    public R modifyPhone(@LoginUser UserEntity user,String phone){
        user.setPhone(phone);
        userService.update(user);
        return R.ok();
    }

    /**
     * 用户查询订单目的地（多目的地）
     */
    @PostMapping("queryPsOrderDes")
    public R queryPsOrderDes(@LoginUser UserEntity user, String ordernum){
        List<Map<String,Object>> destinationList = psOrderRouteSectionService.queryDestinationsByOrderNum(ordernum);

        return R.ok().put("destinationList",destinationList);
    }

    /**
     * 用户查询订单跟踪
     */
    @PostMapping("queryPsOrderLogistics")
    public R queryPsOrderLogistics(@LoginUser UserEntity user, String ordernum){
        Map<String,Object> param = new HashMap<>();
        param.put("orderNum",ordernum);
        List<PsOrderLogisticsRecordEntity> psOrderLogisticsRecords = psOrderLogisticsRecordService.queryList(param);

        return R.ok().put("psOrderLogisticsRecords",psOrderLogisticsRecords);
    }

    @PostMapping("queryPsOrderByOrderNum")
    public R queryPsOrderByOrderNum(@LoginUser UserEntity user,String ordernum){
        PsOrderEntity psOrder = psOrderService.queryByOrderNum(ordernum);

        return R.ok().put("psOrder",psOrder);
    }

}
